<?php
/**
 * Created by PhpStorm.
 * User: liiyu
 * Date: 2018/6/7
 * Time: 1:51
 */

namespace app\api\controller\v16;

use app\api\controller\v2\Auth;
use app\common\cachemodel\Orders as OrdersCacheModel;
use app\common\cachemodel\OrdersLib as OrdersCacheModelLib;
use Exception;
use think\Log;
use think\response\Json;

/**
 * @version 2.0.0
 * 每日运势订单接口
 * Class Orders
 * @package app\api\controller\v2
 */
class Orders extends Auth
{
    /**
     * 接口，订单列表
     * @return Json
     * @throws Exception
     */
    public function index()
    {
        $this->msg = '';
        OrdersCacheModelLib::getUserAllUnpaidOrder($this->user['id']);
        $type = input('param.type/d', 0);
        $order_type = input('param.order_type/s', '');
        $version_code = input('param.version_code/d', 0);

        //1.9.6版本以后不需要过滤本命预测
        if ($version_code)
        {
            switch (true)
            {
                case $this->headers['app-type'] === 'ios' && $version_code >= 22:
                case $this->headers['app-type'] === 'android' && $version_code >= 34:
                    $orders = (new OrdersCacheModel())->getUserAllOrder($this->user['id'], $type, $order_type);
                    break;
                default:
                    $orders = (new OrdersCacheModel())->getUserAllOrder($this->user['id'], $type, $order_type, '7');
                    break;
            }
        } else
        {
            $orders = (new OrdersCacheModel())->getUserAllOrder($this->user['id'], $type, $order_type, '7');
        }
        if ($orders)
        {
            $array = [];
            foreach ($orders['data'] as $k => $order_detail)
            {
                $order = $this->index_data_format($order_detail);
                if ($order)
                {
                    if ($order['trade_type'] == 13 || $order['trade_type'] == 8)
                    {
                        $order['trade_type'] = 2;
                    } elseif ($order['trade_type'] == 7)
                    {
                        $order['trade_type'] = 1;
                    }
                    $array[] = $order;
                }
            }
            $orders['data'] = $array;
        }
        return show(config('code.success'), '加载成功', $orders);
    }

    /**
     * 组合订单列表数据格式
     * @param $order_detail
     * @return array | string
     * @throws Exception
     */
    private function index_data_format($order_detail)
    {
        try
        {
            $order = OrdersCacheModelLib::getOrderDetails($order_detail);
            if ($order === false)
            {
                return $this->msg = '订单数据错乱';
            }
            // 处理苹果审核时价格
            $order_detail['order_type'] = (int)$order_detail['order_type'];
            if ($this->is_apple_pay && $order_detail['order_type'] !== 8)
            {
                switch ($order_detail['order_type'])
                {
                    case 1:
                        $apple_goods = $this->apple_goods['rec_goods'];
                        break;
                    case 2:
                        $apple_goods = $this->apple_goods['fortune_day_goods'];
                        break;
                    case 3:
                        $apple_goods = $this->apple_goods['fortune_month_goods'];
                        break;
                    case 4:
                        $apple_goods = $this->apple_goods['fortune_year_goods'];
                        break;
                    case  5:
                        $apple_goods = $this->apple_goods['acg_goods'];
                        break;
                    case 6:
                        $apple_goods = $this->apple_goods['video_goods'];
                        break;
                    case 7:
                        $apple_goods = $this->apple_goods['natal_report_goods'];
                        break;
//                case 8:
//                    $apple_goods = $this->apple_goods['vip_goods'];
//                    break;
                    default:
                        $apple_goods = [];
                        break;
                }
                $total_amount = 0;
                foreach ($apple_goods as $ag)
                {
                    foreach ($order['goods_data'] as $gid => $odg)
                    {
                        if ((int)$ag['id'] === (int)$odg['id'])
                        {
                            $total_amount += $ag['now_prize'];
                            $order['goods_data'][$gid] = array_merge($odg, $ag);
                        }
                    }
                }
                $order_detail['total_amount'] = $total_amount;
            }
            $data = [];
            $data['data'] = [];
            $order_data = [];
            switch (true)
            {
                //重组校准生辰订单
                case (int)$order_detail['order_type'] === 1:
                    $data['order_name'] = '校准生辰';
                    $order_data['title'] = '校准生辰服务';
                    $order_data['des1'] = '出生时间：' . date('Y-m-d', $order['rectification_data']['start_time']);
                    $order_data['des2'] = '时间范围：' . date('H:i', $order['rectification_data']['start_time']) . '-' . ((date('d', $order['rectification_data']['start_time']) != date('d', $order['rectification_data']['end_time'])) ? '次日' : '') . date('H:i', $order['rectification_data']['end_time']);
                    $data['data'][] = $order_data;
                    break;
                //重组运势订单
                case in_array((int)$order_detail['order_type'], [2, 3, 4], true):
                    switch ($order_detail['order_type'])
                    {
                        case 2:
                            $order_data['title'] = '每日运势';
                            break;
                        case 3:
                            $order_data['title'] = '月度运势';
                            break;
                        case 4:
                            $order_data['title'] = '年度运势';
                            break;
                        default :
                            $order_data['title'] = '';
                            break;
                    }
                    $data['order_name'] = '运势订单';
                    $frame = [];
                    foreach ($order['recode_data'] as $for)
                    {
                        $frame[] = $for['name'];
                        $order_data['des2'] = '有效日期：' . $order['fortune_data']['start_time'] . '至' . $order['fortune_data']['end_time'];
                    }
                    $frame = $frame ? implode(',', $frame) : '';
                    $order_data['des1'] = '开通档案：' . $frame;
                    $data['data'][] = $order_data;
                    break;
                //重组地图订单
                case (int)$order_detail['order_type'] === 5:
                    $data['order_name'] = '幸运之城';
                    $order_data['title'] = '幸运之城解锁';
                    $map_recode = $order['recode_data'] ? current($order['recode_data']) : [];
                    $game = [];
                    foreach ($order['goods_data'] as $acg)
                    {
                        $game[] = $acg['name'];
                    }
                    $map_count = count($game);
                    $gabe_sta = $game ? implode(',', $game) : '';
                    if ($map_count > 2)
                    {
                        $des = '开通' . implode(',', array_slice($game, 0, 2)) . '等' . $map_count . '条';
                    } else
                    {
                        $des = '开通' . $gabe_sta . '等' . $map_count . '条';
                    }
                    $order_data['des1'] = '购买档案：' . $map_recode['name'];
                    $order_data['des2'] = '订单详情：' . $des;
                    $data['order_data'][] = [
                        'name' => '订单详情',
                        'value' => $gabe_sta
                    ];
                    $data['data'][] = $order_data;
                    break;
                //重组本命预测订单
                case (int)$order_detail['order_type'] === 7:
                    $data['order_name'] = '一生报告订单';
                    $order_data['title'] = '一生报告解锁';
                    $game = [];
                    foreach ($order['goods_data'] as $acg)
                    {
                        $game[] = $acg['name'];
                    }
                    $map_count = count($game);
                    $gabe_sta = $game ? implode(',', $game) : '';
                    if ($map_count > 1)
                    {
                        $des = '开通' . implode(',', array_slice($game, 0, 1)) . '等' . $map_count . '篇';
                    } else
                    {
                        $des = '开通' . $gabe_sta;
                    }
                    $order_data['des1'] = $des;
                    $data['order_data'][] = [
                        'name' => '订单详情',
                        'value' => $gabe_sta
                    ];
                    $data['data'][] = $order_data;
                    break;
                //重组视频订单
                case (int)$order_detail['order_type'] === 6:
                    $video_goods = $order['goods_data'] ? current($order['goods_data']) : [];
                    $data['order_name'] = '教学视频';
                    $data['video_id'] = $order['video_id'];
                    $order_data['title'] = $video_goods['name'];
                    $order_data['des1'] = $order['goods_data_des'];
                    $data['data'][] = $order_data;
                    break;
                //重组vip订单
                case (int)$order_detail['order_type'] === 8:
                    $vip_goods = $order['goods_data'] ? current($order['goods_data']) : [];
//                $vip_goods_des = json_decode($vip_goods['extend'], true)['goods_des'] ?? '';
                    $data['order_name'] = '开通会员';
                    $order_data['title'] = '会员开通';
                    $order_data['des1'] = '开通时长：' . $vip_goods['name'];
                    //若会员购买成功后，显示有效期
                    if ((int)$order['status'] === 4)
                    {
                        $order_data['des2'] = '有效期至：' . $order['vip_end_time'];
                    }
                    $data['data'][] = $order_data;
                    break;
            }
            $data['order_type'] = (int)$order_detail['order_type'];
            $data['order_status'] = $order['status_des'];
            $data['order_id'] = $order_detail['order_id'];
            $data['create_time'] = date('Y-m-d H:i:s', $order_detail['create_time']);
            $data['total_amount'] = $order_detail['total_amount'];
            $data['trade_type'] = (int)$order_detail['trade_type'];
            //获取订单按钮数据,列表没有取消订单
            if (isset($order['order_btn'][4]))
            {
                unset($order['order_btn'][4]);
            }
            $data['order_btns'] = $this->getIndexOrderBtn($order_detail);
            $data['mini_type_des'] = $order['mini_type_des'];
            return $data;
        }
        catch (\Exception $e)
        {
            Log::write($this->user['id'] . '订单列表错误：' . $e->getMessage() . '【' . $e->getFile() . $e->getLine() . '】', 'error', true);
        }
        return [];
    }

    /**
     * 获取订单列表按钮
     * @param $orders
     * @return mixed
     */
    private function getIndexOrderBtn($orders)
    {
        // 如果是苹果支付，并且是未支付的情况，去支付在按钮不显示
        if ($orders['trade_type'] == 9 && $orders['status'] == 0)
        {
            return [];
        }
        $bans = config('zhunleorder');
        $data = $bans['index_order_btn'][$orders['status']];
        $array = [];
        if (in_array((int)$orders['status'], [3, 4], true) && in_array((int)$orders['order_type'], [1, 5, 6], true))
        {
            $array[] = array_shift($data);
        } else
        {
            $array = $data;
        }
        return $array;
    }
}
